package com.zhs.gccs.activity.gccs;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.annimon.stream.Stream;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.shape.view.ShapeButton;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zhs.gccs.R;
import com.zhs.gccs.adapter.AdminGccsTaskListAdapter;
import com.zhs.gccs.base.BaseActivity;
import com.zhs.gccs.dialog.GccsDataSearchDialog;
import com.zhs.gccs.dialog.Xzq1Dialog;
import com.zhs.gccs.dialog.Xzq2Dialog;
import com.zhs.gccs.dialog.Xzq3Dialog;
import com.zhs.gccs.http.Api;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.model.CheckBoxModel;
import com.zhs.gccs.model.XzqArea;
import com.zhs.gccs.utils.GsonImpl;
import com.zhs.gccs.utils.OnNoDoubleClickListener;
import com.zhs.gccs.utils.SharedPrefHelper;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.view.gt.DistrictSingleSelectView;
import com.zhs.gccs.view.gt.YearSingleSelectView;
import com.zhs.gccs.vo.AdminTaskBean;
import com.zhs.gccs.vo.TaskAreaBean;
import com.zhs.gccs.vo.TaskListBean;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by chengzf on 2024/7/19.
 */
public class AdminSendTaskActivity extends BaseActivity {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.tv_district)
    TextView tv_district;
    private List<XzqArea> xzqAreas;
    private String province;
    private String city;
    private String district;
//    Dialog dialogDistrict;
//    DistrictSingleSelectView districtSingleSelectView;
    @BindView(R.id.tv_year)
    TextView tv_year;
    Dialog dialogYears;
    YearSingleSelectView yearSingleSelectView;
    @BindView(R.id.iv_search)
    View iv_search;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.fame_bar)
    FrameLayout fame_bar;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.btn_next)
    ShapeButton btn_next;

    private List<AdminTaskBean> gccsTasks;
    private AdminGccsTaskListAdapter gccsTaskAdapter;
    private int pageNum = 0;
    private int pageSize = 10;
    private String year;
    private String xzq;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_send_task_layout);
        ImmersionBar.with(this).transparentBar().statusBarDarkFont(true).init();
        ButterKnife.bind(this);
        fame_bar.setPadding(0, ImmersionBar.getStatusBarHeight(this), 0, 0);

        gccsTasks = new ArrayList<>();
        gccsTaskAdapter  = new AdminGccsTaskListAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(gccsTaskAdapter);
        refreshLayout.setEnableRefresh(true);

        gccsTaskAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                for (int i1 = 0; i1 < gccsTaskAdapter.getData().size(); i1++) {
                    AdminTaskBean taskBean = gccsTaskAdapter.getData().get(i1);
                    if (i == i1){
                        taskBean.setIcCheck(!taskBean.isIcCheck());
                    }else {
                        taskBean.setIcCheck(false);
                    }
                }
                gccsTaskAdapter.setNewData(gccsTaskAdapter.getData());
            }
        });


        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 0;
                getXmDataList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                getXmDataList();
            }
        });
        year = "";
        initView();
        getXmXzq();
        getXmDataList();
    }

    private void initView() {
        iv_back.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                finish();
            }
        });
        btn_next.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                AdminTaskBean taskBean = null;
                for (int i = 0; i < gccsTaskAdapter.getData().size(); i++) {
                    AdminTaskBean bean = gccsTaskAdapter.getData().get(i);
                    if (bean.isIcCheck()){
                        taskBean = bean;
                        break;
                    }
                }
                if (taskBean != null){
                    AdminAssignPersonnelActivity.start(AdminSendTaskActivity.this, taskBean);
                }else {
                    ToastUtils.toast("请先选择任务");
                }
            }
        });

//        districtSingleSelectView = (DistrictSingleSelectView) LayoutInflater.from(context).inflate(
//                R.layout.layout_view_district_single_select2, null);
//        dialogDistrict = bottomDialog(districtSingleSelectView);
//        districtSingleSelectView.setDataChangeListener(new DistrictSingleSelectView.DataChangeListener() {
//            @Override
//            public void dataChange() {
//                List<CheckBoxModel> selectedItems = districtSingleSelectView.getSelectedItems();
//                if(selectedItems!=null&&selectedItems.size()>0){
//                    CheckBoxModel model = selectedItems.get(0);
//                    xzq = model.getValue().toString();
//                    tv_district.setText(model.getTitle());
//                }else {
//                    xzq = "";
//                    tv_district.setText("项目区域");
//                }
//            }
//
//            @Override
//            public void dismis() {
//                if (dialogDistrict != null) dialogDistrict.dismiss();
//            }
//        });
        tv_district.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
//                if (dialogDistrict != null) dialogDistrict.show();
                String xzqOfUser = SharedPrefHelper.getInstance().getUserXzq();
                if(xzqAreas==null||xzqAreas.size()==0)return;
                if("00".equals(xzqOfUser.substring(0,2))){
                    //部级权限--省市区
                    new Xzq3Dialog.Builder(AdminSendTaskActivity.this,
                            "000000",province,city,district,xzqAreas,
                            new Xzq3Dialog.OnSelectedListener() {
                                @Override
                                public void onSelected(String pro, String c, String d) {
                                    province = pro;
                                    city = c;
                                    district = d;
                                    String selectedXzq = TextUtils.isEmpty(district)?city:district;
                                    xzq = selectedXzq;
                                    XzqArea selected = Stream.of(xzqAreas).filter(i -> i.getXzqhdm().equals(selectedXzq)).findFirstOrElse(null);
                                    if(selected!=null){
                                        tv_district.setText(selected.getXzqhmc());
                                    }else {
                                        tv_district.setText("项目区域");
                                    }
                                    pageNum = 0;
                                    getXmDataList();
                                }
                            }).show();
                }else if("0000".equals(xzqOfUser.substring(xzqOfUser.length()-4))){
                    //省级权限--市区
                    new Xzq2Dialog.Builder(AdminSendTaskActivity.this,
                            xzqOfUser,city,district,xzqAreas,
                            new Xzq2Dialog.OnSelectedListener() {
                                @Override
                                public void onSelected(String c, String d) {
                                    city = c;
                                    district = d;
                                    String selectedXzq = TextUtils.isEmpty(district)?city:district;
                                    xzq = selectedXzq;
                                    XzqArea selected = Stream.of(xzqAreas).filter(i -> i.getXzqhdm().equals(selectedXzq)).findFirstOrElse(null);
                                    if(selected!=null){
                                        tv_district.setText(selected.getXzqhmc());
                                    }else {
                                        tv_district.setText("项目区域");
                                    }
                                    pageNum = 0;
                                    getXmDataList();
                                }
                            }).show();
                }
                else if("00".equals(xzqOfUser.substring(xzqOfUser.length()-2))){
                    //市级权限--区
                    new Xzq1Dialog.Builder(AdminSendTaskActivity.this,
                            xzqOfUser,district,xzqAreas,
                            new Xzq1Dialog.OnSelectedListener() {
                                @Override
                                public void onSelected(String d) {
                                    district = d;
                                    String selectedXzq = TextUtils.isEmpty(district)?city:district;
                                    xzq = selectedXzq;
                                    XzqArea selected = Stream.of(xzqAreas).filter(i -> i.getXzqhdm().equals(selectedXzq)).findFirstOrElse(null);
                                    if(selected!=null){
                                        tv_district.setText(selected.getXzqhmc());
                                    }else {
                                        tv_district.setText("项目区域");
                                    }
                                    pageNum = 0;
                                    getXmDataList();
                                }
                            }).show();
                }
                else{//区县--
                    xzq = xzqOfUser;
                    XzqArea selected = Stream.of(xzqAreas).filter(i -> i.getXzqhdm().equals(xzqOfUser)).
                            findFirstOrElse(null);
                    if(selected!=null){
                        tv_district.setText(selected.getXzqhmc());
                    }else {
                        tv_district.setText("项目区域");
                    }
                    pageNum = 0;
                    getXmDataList();
                }
            }
        });


        yearSingleSelectView = (YearSingleSelectView) LayoutInflater.from(context).inflate(
                R.layout.layout_view_year_single_select2, null);
        yearSingleSelectView.initData(2019, Calendar.getInstance().get(Calendar.YEAR));
        dialogYears = bottomDialog(yearSingleSelectView);
        yearSingleSelectView.setDataChangeListener(new YearSingleSelectView.DataChangeListener() {
            @Override
            public void dataChange() {
                List<CheckBoxModel> selectedItems = yearSingleSelectView.getSelectedItems();
                if(selectedItems!=null&&selectedItems.size()>0){
                    CheckBoxModel model = selectedItems.get(0);
                    year = model.getValue().toString();
                    tv_year.setText(model.getTitle());
                }else {
                    year = "";
                    tv_year.setText("立项年份");
                }
            }

            @Override
            public void dismis() {
                if (dialogYears != null) dialogYears.dismiss();
            }
        });
        tv_year.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (dialogYears != null) dialogYears.show();
            }
        });
        iv_search.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                pageNum = 0;
                getXmDataList();
            }
        });
    }
    private Dialog bottomDialog(View view) {
//        View view = LayoutInflater.from(this).inflate(layout, null);
        Dialog dialog = new Dialog(this);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setContentView(view);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        //dialog.show();
        return dialog;
    }

    private void getXmXzq(){
        toSubscribeSingleOb(Api.getDefault()
                        .getGccsXmXzq(),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        TaskAreaBean bean = GsonImpl.get().toObject(result, TaskAreaBean.class);
                        if (bean.getCode() != 200) {
                            ToastUtils.toast("查询失败: " + bean.getMsg());
                            return;
                        }
                        if (bean.getData() == null || bean.getData().size() == 0) return;
//                        String userXzq = SharedPrefHelper.getInstance().getUserXzq();
//                        districtSingleSelectView.initData(userXzq,bean.getData());
                        xzqAreas = bean.getData();
                    }
                    @Override
                    protected void _onError(String result) {
                    }
                });
    }

    private void getXmDataList(){
        showDialog();
        toSubscribeSingleOb(Api.getDefault()
                        .queryTaskxmList(xzq, year, pageSize,pageNum),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        Type type = TypeToken.getParameterized(TaskListBean.class, AdminTaskBean.class).getType();
                        TaskListBean bean = new Gson().fromJson(result, type);//GsonImpl.get().toObject(result, SmTaskBean.class);
//                        AdminTaskListBean bean =  new Gson().fromJson(result, AdminTaskListBean.class);//GsonImpl.get().toObject(result, SmTaskBean.class);
                        if(pageNum==0){
                            gccsTasks.clear();
                        }
                        if (bean != null && bean.getCode() == 200 && bean.getRows() != null&& bean.getRows().size()>0 ) {
                            gccsTasks.addAll(bean.getRows());
                            finishLoadMore();
                            int total = bean.getTotal();
                            if(total>((pageNum+1)*pageSize)){
                                ++pageNum;
                                refreshLayout.setEnableLoadMore(true);
                            }else {
                                refreshLayout.setEnableLoadMore(false);
                            }
                        }else {
                            finishLoadMore();
                            refreshLayout.setEnableLoadMore(false);
                        }
                        gccsTaskAdapter.setNewData(gccsTasks);
                    }
                    @Override
                    protected void _onError(String result) {
                        finishLoadMore();
                        refreshLayout.setEnableLoadMore(false);
                    }
                });
    }

    private void finishLoadMore() {
        dismissDialog();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }



    public static void start(Context context){
        context.startActivity(new Intent(context, AdminSendTaskActivity.class));
    }
}
